﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Kakeibo.Controller {
    class GridPanelController : IController {
        private View.GridPanel gridPanel_;
        private Model.KakeiboDatabase db_;
        private string sqlWhere_;
        private int offset_;
        private int limit_;

        public GridPanelController(Model.KakeiboDatabase db, string sql_where) {
            db_ = db;
            sqlWhere_ = sql_where;
            gridPanel_ = new View.GridPanel();

            limit_ = 100;
            offset_ = 0;
            RefreshGridRows();
        }

        private void RefreshGridRows(){
            string sql = "select transaction_year, transaction_month, transaction_day, debtor.name, subdebtor.name, creditor.name, subcreditor.name, amount from " +
                "kakeibo, category as debtor, category as subdebtor, category as creditor, category as subcreditor where " +
                "debtor.id = kakeibo.debtor_id and creditor.id = kakeibo.creditor_id and subdebtor.id = kakeibo.debtor_sub_id and subcreditor.id = kakeibo.creditor_sub_id ";
            if(sqlWhere_ != null){
                sql += "and (" + sqlWhere_ + " )";
            }
            if (limit_ != 0) {
                sql += " limit " + limit_;
            }
            if (offset_ != 0) {
                sql += " offset " + offset_;
            }
            var rows = db_.ReadData(sql);
            var grid_items = new List<Kakeibo.View.GridPanel.GridItem>(rows.Count);
            foreach (var item in rows) {
                var grid_item = new Kakeibo.View.GridPanel.GridItem(
                    (long)item[0], (long)item[1], (long)item[2], (string)item[3], (string)item[4], (string)item[5], (string)item[6], (long)item[7]
                );
                grid_items.Add(grid_item);

            }
            gridPanel_.SetDataSource(grid_items);
        }

        public View.IView View {
            get { return gridPanel_; }
        }
    }
}
